const db = require("../db/index")
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
const {secretKey,expiresIn} = require("../config/index")
const uuid = require('node-uuid')

//注册
exports.regist = (req,res) => {
    const userInfo = req.body
    const sql = "SELECT * FROM user WHERE account = ?"
    db.query(sql,userInfo.account,(err,results) => {
        //执行SQL失败
        if (err) return res.send({status:0,message:err.message})
        if (results.length > 0) {
            return res.send({status:500,message:'用户已被注册,请更换用户名！'})
        }
        //密码hash加密
        userInfo.password = bcrypt.hashSync(userInfo.password,10)
        //用户UUID
        userInfo.userId = uuid.v1()
        userInfo.name = userInfo.account
        userInfo.userImage = ""
        userInfo.lat = ""
        userInfo.lng = ""
        const sql = "INSERT INTO user SET ?"
        db.query(sql,userInfo,(err,results) => {
            //执行SQL失败
            if (err) return res.send({status:0,message:err.message})
            if (results.affectedRows !== 1) {
                return res.send({ status: 500, message: "注册用户失败，请联系管理员！" });
            }
            res.send({status:200,message:'用户注册成功!'})
        })
    })
    
}

//登录
exports.login = (req,res) => {
    const userInfo = req.body
    const sql = "SELECT * FROM user WHERE account = ?"
    db.query(sql,userInfo.account,(err,results) => {
        if (err) return res.send({status:0,message:err.message})
        if (results.length !== 1) {
            return res.send({status:200,message:'登陆失败，请检查用户名和密码！'})
        }
         // 判断密码是否正确
        const flag = bcrypt.compareSync(userInfo.password, results[0].password);
        if (!flag) return res.send({ status: 403, message: "登录失败，密码错误！" });
        //jwt加密userId 生成token
        const token = jwt.sign({userId:results[0].userId},secretKey,{
            expiresIn:expiresIn
        })
        res.send({
            status:200,
            message:"登录成功",
            token:"Bearer " + token,
            data:results
        })
    })
}


//登录
exports.removeAccount = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        const sql = "DELETE FROM user WHERE userId = ?"
        //如果有多个参数，query的第二个入参是数组
        console.log(userInfo,'userInfo')
        db.query(sql,data.userId,(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            res.send({
                status:200,
                message:"用户已注销",
            })
        })
        
    })
}


//用户第一次登录
exports.firstRegist = (req,res) => {
    const userInfo = req.body
    const sql = "INSERT INTO nn_user SET ?"
        db.query(sql,userInfo,(err,results) => {
            //执行SQL失败
            //jwt加密userId 生成token
            const token = jwt.sign({userId:userInfo.uid},secretKey,{
                expiresIn:expiresIn
            })
            if (err) return res.send({status:0,message:err.message})
            if (results.affectedRows !== 1) {
                return res.send({ status: 500, message: "注册用户失败！" });
            }
            res.send({status:200,message:'用户注册成功!', token:"Bearer " + token})
        })
}


